package org.paysim.payment.service.impl;

import java.util.Map;

import org.paysim.annotation.Channel;
import org.paysim.constant.OrderStatus;
import org.paysim.constant.TradeStatus;
import org.paysim.order.service.IOrderService;
import org.paysim.payment.model.PaymentCancelRequest;
import org.paysim.payment.model.PaymentCancelResponseData;
import org.paysim.payment.model.PaymentInitiateRequest;
import org.paysim.payment.service.IPaymentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeCloseModel;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.easysdk.factory.Factory;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;

@Channel("alipay")
@Service
public class AlipayService implements IPaymentService {
    @Resource
    private AlipayClient alipayClient;

    @Resource
    private IOrderService orderService;

    @Value("${alipay.notifyUrl}")
    private String notifyUrl;

    @Value("${alipay.homeUrl}")
    private String homeUrl;

    public String initiatePayment(PaymentInitiateRequest paymentInitiateRequest) {
        // 构造请求参数以调用接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();

        // 设置商户订单号
        model.setOutTradeNo(paymentInitiateRequest.getOrderId());
        // 设置回调 url
        request.setNotifyUrl(notifyUrl);

        // 设置订单总金额
        model.setTotalAmount(paymentInitiateRequest.getTotalAmount());

        // 设置订单标题
        model.setSubject(paymentInitiateRequest.getsubjectName());

        // 设置产品码
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        // 设置商户自定义二维码宽度
        model.setQrcodeWidth(100L);

        // 设置订单绝对超时时间
        model.setTimeoutExpress("10m");

        request.setBizModel(model);

        // 设置跳转地址
        request.setReturnUrl(homeUrl);
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request, "POST");
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String pageRedirectionData = response.getBody();

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return pageRedirectionData;
    }

    @Override
    public void notifyPayment(Map<String, String> params) {
        // TODO Auto-generated method stub
        try {
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                // TODO 更新本地订单状态 out_trade_no
                String orderId = params.get("out_trade_no");
                String orderStatus = OrderStatus.UNPAID.getStatus();
                if (TradeStatus.TRADE_SUCCESS.getStatus().equals(params.get("trade_status"))) {
                    orderStatus = OrderStatus.PAID.getStatus();
                } else if (TradeStatus.TRADE_FINISHED.getStatus().equals(params.get("trade_status"))) {
                    orderStatus = OrderStatus.COMPLETED.getStatus();
                } else if (TradeStatus.WAIT_BUYER_PAY.getStatus().equals(params.get("trade_status"))) {
                    orderStatus = OrderStatus.PAYING.getStatus();
                } else if (TradeStatus.TRADE_CLOSED.getStatus().equals(params.get("trade_status"))) {
                    orderStatus = OrderStatus.CANCELLED.getStatus();
                } else {
                    // TODO 异常处理，记录日志
                    return;
                }
                orderService.updateOrderStatus(orderId, orderStatus);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public PaymentCancelResponseData cancelPayment(@Valid PaymentCancelRequest paymentCancelRequest) {
        // TODO

        // 构造请求参数以调用接口
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        AlipayTradeCloseModel model = new AlipayTradeCloseModel();

        // 设置订单支付时传入的商户订单号
        String orderId = paymentCancelRequest.getOrderId();
        model.setOutTradeNo(orderId);

        // 设置商家操作员编号 id
        model.setOperatorId("YX01");

        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

        PaymentCancelResponseData paymentCancel = new PaymentCancelResponseData();
        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            // TODO log this error
            e.printStackTrace();
        }
        // TODO 只有原来订单状态为未支付时才更新订单状态为取消
        String originStatus = orderService.queryOrderStatus(orderId);
        if (OrderStatus.UNPAID.getStatus().equals(originStatus)) {
            orderService.updateOrderStatus(orderId, OrderStatus.CANCELLED.getStatus());
        }

        if (response.isSuccess()) {
            System.out.println("调用成功");
            return paymentCancel;
        } else {
            System.out.println("调用失败");
            paymentCancel.setOrderId(orderId);
            paymentCancel.setStatus(TradeStatus.CANCLE_FAILED.getStatus());
            return paymentCancel;
            // TODO 处理异常
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
    }
}
